package com.springboot.elaticsearch.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.elaticsearch.demo.annotation.Document;
import com.springboot.elaticsearch.demo.dao.DmAllplatOrderCompanyCountDayMapper;
import com.springboot.elaticsearch.demo.pojo.DmAllplatOrderCompanyCountDay;
import com.springboot.elaticsearch.demo.service.IDmAllplatOrderCompanyCountDayService;
import com.springboot.elaticsearch.demo.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 企业销售统计表 服务实现类
 * </p>
 *
 * @author jxm
 * @since 2023-03-01
 */
@Service
@Slf4j
public class DmAllplatOrderCompanyCountDayServiceImpl extends ServiceImpl<DmAllplatOrderCompanyCountDayMapper, DmAllplatOrderCompanyCountDay> implements IDmAllplatOrderCompanyCountDayService {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean saveToES() {
        long l = System.currentTimeMillis();
        QueryWrapper<DmAllplatOrderCompanyCountDay> wrapper = new QueryWrapper<>();
//        wrapper.last("limit 0,10000");
        List<DmAllplatOrderCompanyCountDay> list = this.list(wrapper);
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout(TimeValue.timeValueSeconds(120));
        for (int i = 0; i < list.size(); i++) {
            bulkRequest.add(new IndexRequest("order_company")
                    .source(JSON.toJSONString(list.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = null;
        try {
            bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("==================:"+(System.currentTimeMillis()-l));
        return !bulk.hasFailures();
    }

    @Override
    public List<Map<String, Object>> search(String keyword, Integer pageNo, Integer pageSize) {

        SearchRequest searchRequest = new SearchRequest("order_company");

       //构造条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //解除没事只能查询10000条的上限。
//        sourceBuilder.trackTotalHits(true);

        sourceBuilder.from(0);
        sourceBuilder.size(10);

        searchRequest.source(sourceBuilder);



        SearchResponse search = null;
        try {
            search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        SearchHits hits = search.getHits();
        System.out.println("============================"+hits.getTotalHits().value);


        return null;
    }


    /**
     * 查询封装，带分页
     * @param pageNum
     * @param pageSize
     * @return
     * @throws IOException
     */
    @Override
    public PageUtils searchPage(String keyword,int pageNum, int pageSize) throws Exception {
//        Document declaredAnnotation = (Document )s.getDeclaredAnnotation(Document.class);
//        if(declaredAnnotation == null){
//            throw new Exception(String.format("class name: %s can not find Annotation [Document], please check", s.getName()));
//        }
//        String indexName = declaredAnnotation.index();
//        SearchRequest searchRequest = new SearchRequest(indexName);

        int start = (pageNum - 1) * pageSize;
        int end = pageNum  * pageSize;

        SearchRequest searchRequest = new SearchRequest("order_company");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //解除没事只能查询10000条的上限。
        searchSourceBuilder.trackTotalHits(true);

        MatchPhraseQueryBuilder companyName = QueryBuilders.matchPhraseQuery("company_name", keyword);
        searchSourceBuilder.query(companyName);
        searchSourceBuilder.from(start);
        searchSourceBuilder.size(end);

        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        JSONArray jsonArray = new JSONArray();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            JSONObject jsonObject = JSON.parseObject(sourceAsString);
            jsonArray.add(jsonObject);
        }
        log.info("返回总数为：" + hits.getTotalHits());
        int total = (int)hits.getTotalHits().value;

        // 封装分页
        List<DmAllplatOrderCompanyCountDay> list = jsonArray.toJavaList(DmAllplatOrderCompanyCountDay.class);

        /**
         * 分页
         * @param list        列表数据
         * @param totalCount  总记录数
         * @param pageSize    每页记录数
         * @param currPage    当前页数
         */
        PageUtils<DmAllplatOrderCompanyCountDay> page = new PageUtils<>(list,total,pageSize,pageNum);
        return page;
    }
}
